<?php

namespace app\api\model\house;

use app\api\model\Holidays;
use app\api\model\house\House as HouseModel;
use app\common\model\User;
use think\Db;
use think\Model;
use traits\model\SoftDelete;


class House extends Model
{


    use SoftDelete;


    // 表名
    protected $name = 'house';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'house_level_text',
        'house_attr_text',
        'mode_text'
    ];

    public function getHouseLevelTextAttr($value, $data)
    {
        $value = $value ?: ($data['house_level'] ?? '');
        $list = $this->getHouseLevelList();
        return $list[$value] ?? '';
    }

    public function getHouseLevelList()
    {
        return [1=>'普选',2=>'惠选',3=>'乐选',4=>'优选',5=>'尊选'];
    }


    public function getHouseAttrTextAttr($value, $data)
    {
        $value = $value ?: ($data['house_attr'] ?? '');
        $list = $this->getHouseAttrList();
        return $list[$value] ?? '';
    }

    public function getHouseAttrList()
    {
        return [0=>'共享民居',1=>'共享民宿',2=>'共享酒店'];
    }


    public function getModeTextAttr($value, $data)
    {
        $mode = explode(',',$data['mode']);
        $is_group = $data['is_group'];
        $arr = [];
        foreach ($mode as $k=>$v){
            if ($v==2||$v==4){
                if ($is_group==1){
                    array_push($arr,'拼房');
                }
            } elseif ($v==3){
                array_push($arr,'换房');
            }
        }
        return array_unique($arr);
    }

    public function getModeList()
    {
        return [0=>'整房共享',1=>'整房自住',2=>'拼房共享',3=>'免费换房',4=>'自住拼房'];
    }

    //推荐
    public function recommend($params)
    {
        $num = isset($params['num']) ? $params['num'] : 10;
        $city_id = isset($params['city_id']) ? $params['city_id'] : 0;//城市

        $where = ['status'=>1,'is_recommend'=>1];

        $field = 'house_id,house_title,score,house_attr,house_level,mode,share_weekday_price,share_weekend_price,share_highday_price,
        is_group,comment_num';

        if ($city_id){
            //$where['city_id'] = $city_id;
        }

        $list = HouseModel::where($where)
            ->field($field)
            ->order('is_top desc is_recommend desc')
            //->order('createtime desc')
            ->limit($num)->select();

        foreach ($list as $k=>$v){
            $media = HouseMedia::where(['house_id'=>$v['house_id']])
                ->order('createtime asc')->column('media');
            $list[$k]['cover'] = count($media)>0?$media[0]:'';
        }

        return $list;
    }

    //首页
    public function index($params)
    {
        //house_attr 房屋属性,0私人住宅(共享民居),1营运民宿(共享民宿),2酒店客房(共享酒店)
        //mode 共享模式,0整房共享,2拼房共享,3免费换房,4自住拼房
        $num = isset($params['num']) ? $params['num'] : 10;
        $city_id = isset($params['city_id']) ? $params['city_id'] : 0;//城市
        //$checkin_date = isset($params['checkin_date']) ? $params['checkin_date'] : date('Y-m-d');//入住日期
        //$leave_date = isset($params['leave_date']) ? $params['leave_date'] : date('Y-m-d', strtotime(date('Y-m-d') . ' +1 day'));//离开日期

        $date = date('Y-m-d');
        $day_of_week = date('N');

        $holidays = Holidays::where(['type'=>0])->column('date');
        $workdays = Holidays::where(['type'=>1])->column('date');

        $where1 = ['status'=>1,'is_group'=>1];
        $where2 = ['status'=>1,'mode'=>3];
        $where3 = ['status'=>1,'house_attr'=>0];
        //$where3[] = ['exp',Db::raw("FIND_IN_SET('0',mode)")];
        //$where3[] = ['exp',Db::raw("FIND_IN_SET('4',mode)")];
        $where4 = ['status'=>1,'house_attr'=>1];
        //$where4[] = ['exp',Db::raw("FIND_IN_SET('0',mode)")];
        //$where4[] = ['exp',Db::raw("FIND_IN_SET('4',mode)")];
        $where5 = ['status'=>1,'house_attr'=>2];
        //$where5[] = ['exp',Db::raw("FIND_IN_SET('0',mode)")];
        //$where5[] = ['exp',Db::raw("FIND_IN_SET('4',mode)")];

        $field = 'house_id,house_title,score,house_attr,house_level,mode,share_weekday_price,share_weekend_price,share_highday_price,
        is_group,comment_num';

        /*if ($city_id){
            $where1['city_id'] = $city_id;
            $where2['city_id'] = $city_id;
            $where3['city_id'] = $city_id;
            $where4['city_id'] = $city_id;
            $where5['city_id'] = $city_id;
        }*/

        //拼房共享
        $list1 = HouseModel::where($where1)
            ->where('mode','in','2,4')
            ->field($field)
            ->order('createtime desc')
            ->limit($num)->select();

        foreach ($list1 as $k=>$v){
            $media = HouseMedia::where(['house_id'=>$v['house_id']])
                ->order('createtime asc')->column('media');
            $list1[$k]['cover'] =  count($media)>0?$media[0]:'';
            if (in_array($date, $holidays)) {
                $list1[$k]['today_price'] = $v['share_highday_price'];
                continue;
            } else {
                if ($day_of_week == 6 || $day_of_week == 7) {
                    if (!in_array($date, $workdays)){
                        $list1[$k]['today_price'] = $v['share_weekend_price'];
                    } else {
                        $list1[$k]['today_price'] = $v['share_weekday_price'];
                    }
                    continue;
                } else {
                    $list1[$k]['today_price'] = $v['share_weekday_price'];
                }
            }
        }
        //免费换房
        $list2 = HouseModel::where($where2)
            ->field($field)
            ->order('createtime desc')
            ->limit($num)->select();

        foreach ($list2 as $k=>$v){
            $media = HouseMedia::where(['house_id'=>$v['house_id']])
                ->order('createtime asc')->column('media');
            $list2[$k]['cover'] =  count($media)>0?$media[0]:'';
            if (in_array($date, $holidays)) {
                $list2[$k]['today_price'] = $v['share_highday_price'];
                continue;
            } else {
                if ($day_of_week == 6 || $day_of_week == 7) {
                    if (!in_array($date, $workdays)){
                        $list2[$k]['today_price'] = $v['share_weekend_price'];
                    } else {
                        $list2[$k]['today_price'] = $v['share_weekday_price'];
                    }
                    continue;
                } else {
                    $list2[$k]['today_price'] = $v['share_weekday_price'];
                }
            }
        }

        //共享民居
        $list3 = HouseModel::where($where3)
            ->field($field)
            ->order('createtime desc')
            ->limit($num)->select();

        foreach ($list3 as $k=>$v){
            $media = HouseMedia::where(['house_id'=>$v['house_id']])
                ->order('createtime asc')->column('media');
            $list3[$k]['cover'] =  count($media)>0?$media[0]:'';
            if (in_array($date, $holidays)) {
                $list3[$k]['today_price'] = $v['share_highday_price'];
                continue;
            } else {
                if ($day_of_week == 6 || $day_of_week == 7) {
                    if (!in_array($date, $workdays)){
                        $list3[$k]['today_price'] = $v['share_weekend_price'];
                    } else {
                        $list3[$k]['today_price'] = $v['share_weekday_price'];
                    }
                    continue;
                } else {
                    $list3[$k]['today_price'] = $v['share_weekday_price'];
                }
            }
        }
        //共享民宿
        $list4 = HouseModel::where($where4)
            ->field($field)
            ->order('createtime desc')
            ->limit($num)->select();

        foreach ($list4 as $k=>$v){
            $media = HouseMedia::where(['house_id'=>$v['house_id']])
                ->order('createtime asc')->column('media');
            $list4[$k]['cover'] =  count($media)>0?$media[0]:'';
            if (in_array($date, $holidays)) {
                $list4[$k]['today_price'] = $v['share_highday_price'];
                continue;
            } else {
                if ($day_of_week == 6 || $day_of_week == 7) {
                    if (!in_array($date, $workdays)){
                        $list4[$k]['today_price'] = $v['share_weekend_price'];
                    } else {
                        $list4[$k]['today_price'] = $v['share_weekday_price'];
                    }
                    continue;
                } else {
                    $list4[$k]['today_price'] = $v['share_weekday_price'];
                }
            }
        }
        //酒店预定
        $list5 = HouseModel::where($where5)
            ->field($field)
            ->order('createtime desc')
            ->limit($num)->select();

        foreach ($list5 as $k=>$v){
            $media = HouseMedia::where(['house_id'=>$v['house_id']])
                ->order('createtime asc')->column('media');
            $list5[$k]['cover'] =  count($media)>0?$media[0]:'';
            if (in_array($date, $holidays)) {
                $list5[$k]['today_price'] = $v['share_highday_price'];
                continue;
            } else {
                if ($day_of_week == 6 || $day_of_week == 7) {
                    if (!in_array($date, $workdays)){
                        $list5[$k]['today_price'] = $v['share_weekend_price'];
                    } else {
                        $list5[$k]['today_price'] = $v['share_weekday_price'];
                    }
                    continue;
                } else {
                    $list5[$k]['today_price'] = $v['share_weekday_price'];
                }
            }
        }
        $data = [
            'pfgx'=>$list1,//拼房共享
            'mfhf'=>$list2,//免费换房
            'gxmj'=>$list3,//共享民居
            'gxms'=>$list4,//共享民宿
            'jdyd'=>$list5,//酒店预定
        ];

        return $data;
    }

    //排名
    public function ranking($params)
    {
        $city_id = isset($params['city_id']) ? $params['city_id'] : 0;//城市
        $num = isset($params['num']) ? $params['num'] : 10;

        $where = ['status'=>1];

        /*if ($city_id){
            $where['city_id'] = $city_id;
        }*/

        $field = 'house_id,house_title,score,house_attr,house_level,mode,share_weekday_price,share_weekend_price,share_highday_price,
        is_group,comment_num,house_facilities_id,group_weekday_price,group_weekend_price,group_highday_price,describe_score,location_score,
        convenient_score,service_score,health_score,cost_performance_score';

        $list = HouseModel::where($where)
            ->field($field)
            ->order('comment_num desc')
            ->paginate($num, false, ['query' => request()->get()]);

        $holidays = Holidays::where(['type'=>0])->column('date');
        $workdays = Holidays::where(['type'=>1])->column('date');

        $date = date('Y-m-d');
        $day_of_week = date('N');

        foreach ($list as $k=>$v){
            $media = HouseMedia::where(['house_id'=>$v['house_id']])
                ->order('createtime asc')->column('media');
            $list[$k]['cover'] =  count($media)>0?$media[0]:'';

            if (in_array($date, $holidays)) {
                $list[$k]['today_price'] = $v['share_highday_price'];
                $group_price_arr = $v['group_highday_price'];
                //continue;
            } else {
                if ($day_of_week == 6 || $day_of_week == 7) {
                    if (!in_array($date, $workdays)){
                        $list[$k]['today_price'] = $v['share_weekend_price'];
                        $group_price_arr = $v['group_weekend_price'];
                    } else {
                        $list[$k]['today_price'] = $v['share_weekday_price'];
                        $group_price_arr = $v['group_weekday_price'];
                    }
                    //continue;
                } else {
                    $list[$k]['today_price'] = $v['share_weekday_price'];
                    $group_price_arr = $v['group_weekday_price'];
                }
            }
            $price_arr = [$v['share_highday_price'],$v['share_weekend_price'],$v['share_weekday_price']];
            $list[$k]['mark_price'] = max($price_arr);
            $group_price_arr = json_decode($group_price_arr,true);
            foreach ($group_price_arr as $kk=>$vv){
                if ($vv['type']=='all'){
                    $group_price_arr[$kk]['title'] = '整房';
                } else {
                    $group_price_arr[$kk]['title'] = '卧室'.$vv['type'];
                }
            }
            $list[$k]['group_price'] = $group_price_arr;
        }

        return $list;
    }

    //编号直达
    public function mylist($user_id)
    {
        $field = 'house_id,house_title,house_code,mode,is_group';
        $where = [
            'user_id'=>$user_id
        ];
        $list = HouseModel::where($where)
            ->field($field)
            ->order('createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);

        return $list;
    }

    //房源列表
    public function lists($params)
    {
        $num = isset($params['num']) ? $params['num'] : 10;
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';//关键词搜索
        $city_id = isset($params['city_id']) ? $params['city_id'] : 0;//城市
        $house_level = isset($params['house_level']) ? $params['house_level'] : 'all';//房屋等级
        $bed_num = isset($params['bed_num']) ? $params['bed_num'] : 0;//床铺数
        $min_price = isset($params['min_price']) ? $params['min_price'] : '';//最小价格
        $max_price = isset($params['max_price']) ? $params['max_price'] : '';//最大价格
        $evaluate_score = isset($params['evaluate_score']) ? $params['evaluate_score'] : '';//评分
        $evaluate_num = isset($params['evaluate_num']) ? $params['evaluate_num'] : '';//点评数
        $mode = isset($params['mode']) ? $params['mode'] : '';//共享模式,0整房共享,2拼房共享,3免费换房
        $facilities = isset($params['facilities']) ? $params['facilities'] : '';//房屋设施
        $people_num = isset($params['people_num']) ? $params['people_num'] : 0;//人数
        $bedroom = isset($params['bedroom']) ? $params['bedroom'] : 0;//居室数
        $user_id = isset($params['user_id']) ? $params['user_id'] : 0;//业主id
        //$checkin_date = isset($params['checkin_date']) ? $params['checkin_date'] : date('Y-m-d');//入住日期
        //$leave_date = isset($params['leave_date']) ? $params['leave_date'] : date('Y-m-d', strtotime(date('Y-m-d') . ' +1 day'));//离开日期

        $where = ['status'=>1];

        /*if ($city_id){
            $where['city_id'] = $city_id;
        }*/
        if ($user_id){
            $where['user_id'] = $user_id;
        }
        if(!empty($keyword)){
            $where['house_title'] = ['like',"%$keyword%"];
        }
        if ($house_level!='all'){
            $where['house_level'] = $house_level;
        }
        if ($bed_num){
            $where['bed_num'] = $bed_num;
        }
        if ($min_price!=''&&$max_price!=''){
            $where['share_weekday_price'] = ['between', [$min_price, $min_price]];
        }
        if ($evaluate_score==1){
            //95分以上
            $where['score'] = ['>',95];
        } elseif ($evaluate_score==2){
            //90分以上
            $where['score'] = ['>',90];
        } elseif ($evaluate_score==3){
            //80分以上
            $where['score'] = ['>',80];
        }
        if ($mode!=''){
            if ($mode==2){
                $where['is_group'] = 1;
            }
            $where['mode'] = $mode;
        }
        if ($facilities){
            $facilities_arr = explode(',',$facilities);
            foreach ($facilities_arr as $k=>$v){
                $where[] = ['exp',Db::raw("FIND_IN_SET('$v',house_facilities_id)")];
            }
        }
        if($people_num){
            $where['bed_limit_people_num'] = ['>',$people_num];
        }
        if($bedroom){
            $where['bedroom_num'] = $bedroom;
        }

        if ($evaluate_num==1){
            //100+点评
            $where['comment_num'] = ['>',100];
        } elseif ($evaluate_num==2){
            //50+点评
            $where['comment_num'] = ['>',50];
        } elseif ($evaluate_num==3){
            //10+点评
            $where['comment_num'] = ['>',10];
        }

        $field = 'house_id,house_title,score,house_attr,house_level,mode,share_weekday_price,share_weekend_price,share_highday_price,
        is_group,comment_num,house_facilities_id,group_weekday_price,group_weekend_price,group_highday_price,describe_score,location_score,
        convenient_score,service_score,health_score,cost_performance_score';

        $list = HouseModel::where($where)
            ->field($field)
            ->order('createtime desc')
            ->paginate($num, false, ['query' => request()->get()]);

        $holidays = Holidays::where(['type'=>0])->column('date');
        $workdays = Holidays::where(['type'=>1])->column('date');

        $date = date('Y-m-d');
        $day_of_week = date('N');

        foreach ($list as $k=>$v){
            $media = HouseMedia::where(['house_id'=>$v['house_id']])
                ->order('createtime asc')->column('media');
            $list[$k]['cover'] =  count($media)>0?$media[0]:'';

            if (in_array($date, $holidays)) {
                $list[$k]['today_price'] = $v['share_highday_price'];
                $group_price_arr = $v['group_highday_price'];
                //continue;
            } else {
                if ($day_of_week == 6 || $day_of_week == 7) {
                    if (!in_array($date, $workdays)){
                        $list[$k]['today_price'] = $v['share_weekend_price'];
                        $group_price_arr = $v['group_weekend_price'];
                    } else {
                        $list[$k]['today_price'] = $v['share_weekday_price'];
                        $group_price_arr = $v['group_weekday_price'];
                    }
                    //continue;
                } else {
                    $list[$k]['today_price'] = $v['share_weekday_price'];
                    $group_price_arr = $v['group_weekday_price'];
                }
            }
            $price_arr = [$v['share_highday_price'],$v['share_weekend_price'],$v['share_weekday_price']];
            $list[$k]['mark_price'] = max($price_arr);
            $group_price_arr = json_decode($group_price_arr,true);
            foreach ($group_price_arr as $kk=>$vv){
                if ($vv['type']=='all'){
                    $group_price_arr[$kk]['title'] = '整房';
                } else {
                    $group_price_arr[$kk]['title'] = '卧室'.$vv['type'];
                }
            }
            $list[$k]['group_price'] = $group_price_arr;
        }

        return $list;
    }

    //申请房源
    public function apply($params)
    {
        $user_id = $params['user_id'];
        $house_param = $params['house'];
        $park_param = $params['park'];
        $park_id = isset($park_param['park_id']) ? $park_param['park_id'] : 0;

        $bed_info = json_decode($house_param['bed_info'],true)?json_decode($house_param['bed_info'],true):_json_decode($house_param['bed_info']);
        $media_json = json_decode($house_param['media_json'],true)?json_decode($house_param['media_json'],true):_json_decode($house_param['media_json']);
        $receive_time = json_decode($house_param['receive_time'],true)?json_decode($house_param['receive_time'],true):_json_decode($house_param['receive_time']);
        $group_weekday_price = json_decode($house_param['group_weekday_price'],true)?json_decode($house_param['group_weekday_price'],true):_json_decode($house_param['group_weekday_price']);
        $group_weekend_price = json_decode($house_param['group_weekend_price'],true)?json_decode($house_param['group_weekend_price'],true):_json_decode($house_param['group_weekend_price']);
        $group_highday_price = json_decode($house_param['group_highday_price'],true)?json_decode($house_param['group_highday_price'],true):_json_decode($house_param['group_highday_price']);
        $complement_json = json_decode($house_param['complement_json'],true)?json_decode($house_param['complement_json'],true):_json_decode($house_param['complement_json']);
        $stay_discount = json_decode($house_param['stay_discount'],true)?json_decode($house_param['stay_discount'],true):_json_decode($house_param['stay_discount']);
        $group_stay_discount = json_decode($house_param['group_stay_discount'],true)?json_decode($house_param['group_stay_discount'],true):_json_decode($house_param['group_stay_discount']);
        $house_model = new House();
        $bed_num = array_sum(array_column($bed_info,'bed_num'));
        $bed_limit_people_num = array_sum(array_column($bed_info,'limit_people_num'));
        Db::startTrans();
        try {

            $house_data = [
                'user_id'=>$user_id,
                'house_title'=>$house_param['house_title'],
                'address'=>$house_param['address'],
                'lat'=>$house_param['lat'],
                'lng'=>$house_param['lng'],
                'province'=>$house_param['province'],
                'province_id'=>$house_param['province_id'],
                'city'=>$house_param['city'],
                'city_id'=>$house_param['city_id'],
                'house_number'=>$house_param['house_number'],
                'area'=>$house_param['area'],
                'community'=>$house_param['community'],
                'house_attr'=>$house_param['house_attr'],
                'bedroom_num'=>$house_param['bedroom_num'],
                'livingroom_num'=>$house_param['livingroom_num'],
                'kitchen_num'=>$house_param['kitchen_num'],
                'bathroom_num'=>$house_param['bathroom_num'],
                'house_type_id'=>$house_param['house_type_id'],
                'house_property_cert_img'=>$house_param['house_property_cert_img'],
                'purchase_contract_time'=>$house_param['purchase_contract_time'],
                'purchase_contract_img'=>$house_param['purchase_contract_img'],
                'evaluation_report_img'=>$house_param['evaluation_report_img'],
                'renovation_contract_img'=>$house_param['renovation_contract_img'],
                'renovation_contract_time'=>$house_param['renovation_contract_time'],
                'insurance_contract_img'=>$house_param['insurance_contract_img'],
                'insurance_contract_time'=>$house_param['insurance_contract_time'],
                'unit_price'=>$house_param['unit_price'],
                'total_area'=>$house_param['total_area'],
                'total_price'=>$house_param['total_price'],
                'decorate_price'=>$house_param['decorate_price'],
                'average_price'=>$house_param['average_price'],
                'insurance_price'=>$house_param['insurance_price'],
                'is_insurance'=>$house_param['is_insurance'],
                //'hotel_level'=>$house_param['hotel_level'],
                //'house_level'=>$house_param['house_level'],
                'bed_num'=>$bed_num,
                'bed_limit_people_num'=>$bed_limit_people_num,
                //'bed_index'=>$house_param['bed_index'],
                'mode'=>$house_param['mode'],
                'live_start_date'=>$house_param['live_start_date'],
                'live_end_date'=>$house_param['live_end_date'],
                'house_facilities_id'=>$house_param['house_facilities_id'],
                'min_live_day'=>$house_param['min_live_day'],
                'max_live_day'=>$house_param['max_live_day'],
                'live_time'=>$house_param['live_time'],
                'leave_time'=>$house_param['leave_time'],
                'receive_time'=>$receive_time?json_encode($receive_time,320):'',
                'sheet_change'=>$house_param['sheet_change'],
                'clean'=>$house_param['clean'],
                'share_weekday_price'=>$house_param['share_weekday_price'],
                'share_weekend_price'=>$house_param['share_weekend_price'],
                'share_highday_price'=>$house_param['share_highday_price'],
                'stay_discount'=>$stay_discount?json_encode($stay_discount,320):'',
                'group_stay_discount'=>$group_stay_discount?json_encode($group_stay_discount,320):'',
                'group_weekday_price'=>$group_weekday_price?json_encode($group_weekday_price,320):'',
                'group_weekend_price'=>$group_weekend_price?json_encode($group_weekend_price,320):'',
                'group_highday_price'=>$group_highday_price?json_encode($group_highday_price,320):'',
                'is_group'=>$house_param['is_group'],
                'house_code'=>date("Ymdhis")  . mt_rand(1000, 9999),
                'park_id'=>$park_id
                //'scenic_id'=>$park_param['scenic_id'],
            ];

            if ($house_data['house_attr']!=2){
                $house_level = $this->calculateHouseLevel($house_data['decorate_price'],$house_data['total_price']);
                $house_data['house_level'] =  $house_level;
                if (empty($house_data['unit_price'])){
                    throw new \Exception('请输入单价');
                }
                if (empty($house_data['total_area'])){
                    throw new \Exception('请输入总面积');
                }
                if (empty($house_data['total_price'])){
                    throw new \Exception('请输入总价');
                }
                if (empty($house_data['decorate_price'])){
                    throw new \Exception('请输入装修费用');
                }
                if (empty($house_data['average_price'])){
                    throw new \Exception('请输入社区房屋均价');
                }
            } else {
                $house_data['house_level'] =  $house_param['house_level'];
            }


            $result = $house_model->validate('House.add')->save($house_data);
            if ($result === false) {
                exception($house_model->getError());
            }
            $house_id = $house_model->house_id;

            //添加图片视频
            $media_model = new HouseMedia();
            $media_list = [];
            foreach ($media_json as $k=>$v){
                $media_list[] = [
                    'house_id'=>$house_id,
                    'category_id'=>$v['category_id'],
                    'media'=>$v['media'],
                ];
            }
            $media_model->saveAll($media_list);

            //房屋的卧室床铺信息
            $bed_info_model = new HouseBedInfo();
            $bed_list = [];
            foreach ($bed_info as $k=>$v){
                $bed_list[] = [
                    'house_id'=>$house_id,
                    'index'=>$v['index'],
                    'bed_name'=>'卧室'.$v['index'],
                    'bed_type'=>$v['bed_type'],
                    'bed_num'=>$v['bed_num'],
                    'live_people_num'=>$v['live_people_num'],
                    'limit_people_num'=>$v['limit_people_num'],
                ];
            }
            $bed_info_model->saveAll($bed_list);


            //房屋的服务项目
            $complement_price_model = new HouseComplementPrice();
            $complement_price_list = [];
            foreach ($complement_json as $k=>$v){
                $complement_price_list[] = [
                    'house_id'=>$house_id,
                    'name'=>$v['name'],
                    'unit'=>$v['unit'],
                    'price'=>$v['price'],
                ];
            }
            $complement_price_model->saveAll($complement_price_list);

            //添加园区
            $park_model = new HousePark();
            $park_res = $park_model->add($user_id,$house_id,$park_param);
            //dump($park_res);die;
            if ($park_res['code']==0){

                Db::rollback();
                throw new \Exception($park_res['msg']);
            }

            Db::commit();
            return $result;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage());
        }

    }

    public function edit($params)
    {
        //$user_id = $params['user_id'];
        $house_id = $params['house']['house_id'];
        $house_param = $params['house'];
        $park_param = $params['park'];
        $park_id = $params['park']['park_id'];

        $bed_info = json_decode($house_param['bed_info'],true)?json_decode($house_param['bed_info'],true):_json_decode($house_param['bed_info']);
        $media_json = json_decode($house_param['media_json'],true)?json_decode($house_param['media_json'],true):_json_decode($house_param['media_json']);
        $receive_time = json_decode($house_param['receive_time'],true)?json_decode($house_param['receive_time'],true):_json_decode($house_param['receive_time']);
        $group_weekday_price = json_decode($house_param['group_weekday_price'],true)?json_decode($house_param['group_weekday_price'],true):_json_decode($house_param['group_weekday_price']);
        $group_weekend_price = json_decode($house_param['group_weekend_price'],true)?json_decode($house_param['group_weekend_price'],true):_json_decode($house_param['group_weekend_price']);
        $group_highday_price = json_decode($house_param['group_highday_price'],true)?json_decode($house_param['group_highday_price'],true):_json_decode($house_param['group_highday_price']);
        $complement_json = json_decode($house_param['complement_json'],true)?json_decode($house_param['complement_json'],true):_json_decode($house_param['complement_json']);
        $stay_discount = json_decode($house_param['stay_discount'],true)?json_decode($house_param['stay_discount'],true):_json_decode($house_param['stay_discount']);
        $group_stay_discount = json_decode($house_param['group_stay_discount'],true)?json_decode($house_param['group_stay_discount'],true):_json_decode($house_param['group_stay_discount']);
        $house_model = new House();
        $bed_num = array_sum(array_column($bed_info,'bed_num'));
        $bed_limit_people_num = array_sum(array_column($bed_info,'limit_people_num'));
        Db::startTrans();
        try {

            $house_data = [
                'house_title'=>$house_param['house_title'],
                'address'=>$house_param['address'],
                'lat'=>$house_param['lat'],
                'lng'=>$house_param['lng'],
                'province'=>$house_param['province'],
                'province_id'=>$house_param['province_id'],
                'city'=>$house_param['city'],
                'city_id'=>$house_param['city_id'],
                'house_number'=>$house_param['house_number'],
                'area'=>$house_param['area'],
                'community'=>$house_param['community'],
                'house_attr'=>$house_param['house_attr'],
                'bedroom_num'=>$house_param['bedroom_num'],
                'livingroom_num'=>$house_param['livingroom_num'],
                'kitchen_num'=>$house_param['kitchen_num'],
                'bathroom_num'=>$house_param['bathroom_num'],
                'house_type_id'=>$house_param['house_type_id'],
                'house_property_cert_img'=>$house_param['house_property_cert_img'],
                'purchase_contract_time'=>$house_param['purchase_contract_time'],
                'purchase_contract_img'=>$house_param['purchase_contract_img'],
                'evaluation_report_img'=>$house_param['evaluation_report_img'],
                'renovation_contract_img'=>$house_param['renovation_contract_img'],
                'renovation_contract_time'=>$house_param['renovation_contract_time'],
                'insurance_contract_img'=>$house_param['insurance_contract_img'],
                'insurance_contract_time'=>$house_param['insurance_contract_time'],
                'unit_price'=>$house_param['unit_price'],
                'total_area'=>$house_param['total_area'],
                'total_price'=>$house_param['total_price'],
                'decorate_price'=>$house_param['decorate_price'],
                'average_price'=>$house_param['average_price'],
                'insurance_price'=>$house_param['insurance_price'],
                'is_insurance'=>$house_param['is_insurance'],
                //'hotel_level'=>$house_param['hotel_level'],
                //'house_level'=>$house_param['house_level'],
                'bed_num'=>$bed_num,
                'bed_limit_people_num'=>$bed_limit_people_num,
                //'bed_index'=>$house_param['bed_index'],
                'mode'=>$house_param['mode'],
                'live_start_date'=>$house_param['live_start_date'],
                'live_end_date'=>$house_param['live_end_date'],
                'house_facilities_id'=>$house_param['house_facilities_id'],
                'min_live_day'=>$house_param['min_live_day'],
                'max_live_day'=>$house_param['max_live_day'],
                'live_time'=>$house_param['live_time'],
                'leave_time'=>$house_param['leave_time'],
                'receive_time'=>$receive_time?json_encode($receive_time,320):'',
                'sheet_change'=>$house_param['sheet_change'],
                'clean'=>$house_param['clean'],
                'share_weekday_price'=>$house_param['share_weekday_price'],
                'share_weekend_price'=>$house_param['share_weekend_price'],
                'share_highday_price'=>$house_param['share_highday_price'],
                'stay_discount'=>$stay_discount?json_encode($stay_discount,320):'',
                'group_stay_discount'=>$group_stay_discount?json_encode($group_stay_discount,320):'',
                'group_weekday_price'=>$group_weekday_price?json_encode($group_weekday_price,320):'',
                'group_weekend_price'=>$group_weekend_price?json_encode($group_weekend_price,320):'',
                'group_highday_price'=>$group_highday_price?json_encode($group_highday_price,320):'',
                'is_group'=>$house_param['is_group'],
            ];

            if ($house_data['house_attr']!=2){
                $house_level = $this->calculateHouseLevel($house_data['decorate_price'],$house_data['total_price']);
                $house_data['house_level'] =  $house_level;
                if (empty($house_data['unit_price'])){
                    throw new \Exception('请输入单价');
                }
                if (empty($house_data['total_area'])){
                    throw new \Exception('请输入总面积');
                }
                if (empty($house_data['total_price'])){
                    throw new \Exception('请输入总价');
                }
                if (empty($house_data['decorate_price'])){
                    throw new \Exception('请输入装修费用');
                }
                if (empty($house_data['average_price'])){
                    throw new \Exception('请输入社区房屋均价');
                }
            } else {
                $house_data['house_level'] =  $house_param['house_level'];
            }

            $result = $house_model->save($house_data,['house_id'=>$house_id]);
            if ($result === false) {
                exception($house_model->getError());
            }
            //$house_id = $house_model->house_id;

            //添加图片视频
            HouseMedia::where(['house_id'=>$house_id])->delete();
            $media_model = new HouseMedia();
            $media_list = [];
            foreach ($media_json as $k=>$v){
                $media_list[] = [
                    'house_id'=>$house_id,
                    'category_id'=>$v['category_id'],
                    'media'=>$v['media'],
                ];
            }
            $media_model->saveAll($media_list);

            //房屋的卧室床铺信息
            HouseBedInfo::where(['house_id'=>$house_id])->delete();
            $bed_info_model = new HouseBedInfo();
            $bed_list = [];
            foreach ($bed_info as $k=>$v){
                $bed_list[] = [
                    'house_id'=>$house_id,
                    'index'=>$v['index'],
                    'bed_name'=>'卧室'.$v['index'],
                    'bed_type'=>$v['bed_type'],
                    'bed_num'=>$v['bed_num'],
                    'live_people_num'=>$v['live_people_num'],
                    'limit_people_num'=>$v['limit_people_num'],
                ];
            }
            $bed_info_model->saveAll($bed_list);


            //房屋的服务项目
            HouseComplementPrice::where(['house_id'=>$house_id])->delete();
            $complement_price_model = new HouseComplementPrice();
            $complement_price_list = [];
            foreach ($complement_json as $k=>$v){
                $complement_price_list[] = [
                    'house_id'=>$house_id,
                    'name'=>$v['name'],
                    'unit'=>$v['unit'],
                    'price'=>$v['price'],
                ];
            }
            $complement_price_model->saveAll($complement_price_list);

            //添加园区
            $park_model = new HousePark();
            $park_res = $park_model->edit($park_id,$park_param);
            //dump($park_res);die;
            if ($park_res['code']==0){

                Db::rollback();
                throw new \Exception($park_res['msg']);
            }

            Db::commit();
            return $result;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage());
        }

    }

    //编辑房源
    public function oldedit($params)
    {
        $user_id = $params['user_id'];
        $house_id = $params['house_id'];
        $bed_info = json_decode($params['bed_info'],true)?json_decode($params['bed_info'],true):_json_decode($params['bed_info']);
        $media_json = json_decode($params['media_json'],true)?json_decode($params['media_json'],true):_json_decode($params['media_json']);
        $receive_time = json_decode($params['receive_time'],true)?json_decode($params['receive_time'],true):_json_decode($params['receive_time']);
        $group_weekday_price = json_decode($params['group_weekday_price'],true)?json_decode($params['group_weekday_price'],true):_json_decode($params['group_weekday_price']);
        $group_weekend_price = json_decode($params['group_weekend_price'],true)?json_decode($params['group_weekend_price'],true):_json_decode($params['group_weekend_price']);
        $group_highday_price = json_decode($params['group_highday_price'],true)?json_decode($params['group_highday_price'],true):_json_decode($params['group_highday_price']);
        $complement_json = json_decode($params['complement_json'],true)?json_decode($params['complement_json'],true):_json_decode($params['complement_json']);
        $stay_discount = json_decode($params['stay_discount'],true)?json_decode($params['stay_discount'],true):_json_decode($params['stay_discount']);
        $group_stay_discount = json_decode($params['group_stay_discount'],true)?json_decode($params['group_stay_discount'],true):_json_decode($params['group_stay_discount']);

        $bed_num = array_sum(array_column($bed_info,'bed_num'));
        $bed_limit_people_num = array_sum(array_column($bed_info,'limit_people_num'));
        $house_model = new House();

        Db::startTrans();
        try {
            $house_data = [
                'house_title'=>$params['house_title'],
                'bed_num'=>$bed_num,
                'bed_limit_people_num'=>$bed_limit_people_num,
                //'bed_index'=>$params['bed_index'],
                'mode'=>$params['mode'],
                'live_start_date'=>$params['live_start_date'],
                'live_end_date'=>$params['live_end_date'],
                'house_facilities_id'=>$params['house_facilities_id'],
                'min_live_day'=>$params['min_live_day'],
                'max_live_day'=>$params['max_live_day'],
                'live_time'=>$params['live_time'],
                'leave_time'=>$params['leave_time'],
                'receive_time'=>$receive_time?json_encode($receive_time,320):'',
                'sheet_change'=>$params['sheet_change'],
                'clean'=>$params['clean'],
                'share_weekday_price'=>$params['share_weekday_price'],
                'share_weekend_price'=>$params['share_weekend_price'],
                'share_highday_price'=>$params['share_highday_price'],
                'stay_discount'=>$stay_discount?json_encode($stay_discount,320):'',
                'group_stay_discount'=>$group_stay_discount?json_encode($group_stay_discount,320):'',
                'group_weekday_price'=>$group_weekday_price?json_encode($group_weekday_price,320):'',
                'group_weekend_price'=>$group_weekend_price?json_encode($group_weekend_price,320):'',
                'group_highday_price'=>$group_highday_price?json_encode($group_highday_price,320):'',
                'is_group'=>$params['is_group'],
            ];

            $result = $house_model->save($house_data,['house_id'=>$house_id]);

            //$house_id = $house_model->house_id;

            //添加图片视频
            HouseMedia::where(['house_id'=>$house_id])->delete();
            $media_model = new HouseMedia();
            $media_list = [];
            foreach ($media_json as $k=>$v){
                $media_list[] = [
                    'house_id'=>$house_id,
                    'category_id'=>$v['category_id'],
                    'media'=>$v['media'],
                ];
            }
            $media_model->saveAll($media_list);

            //房屋的卧室床铺信息
            HouseBedInfo::where(['house_id'=>$house_id])->delete();
            $bed_info_model = new HouseBedInfo();
            $bed_list = [];
            foreach ($bed_info as $k=>$v){
                $bed_list[] = [
                    'house_id'=>$house_id,
                    'index'=>$v['index'],
                    'bed_name'=>'卧室'.$v['index'],
                    'bed_type'=>$v['bed_type'],
                    'bed_num'=>$v['bed_num'],
                    'live_people_num'=>$v['live_people_num'],
                    'limit_people_num'=>$v['limit_people_num'],
                ];
            }
            $bed_info_model->saveAll($bed_list);


            //房屋的服务项目
            HouseComplementPrice::where(['house_id'=>$house_id])->delete();
            $complement_price_model = new HouseComplementPrice();
            $complement_price_list = [];
            foreach ($complement_json as $k=>$v){
                $complement_price_list[] = [
                    'house_id'=>$house_id,
                    'name'=>$v['name'],
                    'unit'=>$v['unit'],
                    'price'=>$v['price'],
                ];
            }
            $complement_price_model->saveAll($complement_price_list);

            //查共享房屋的最高等级就是业主等级
            $change_house_level = House::where(['status'=>1,'user_id'=>$user_id])
                ->where('FIND_IN_SET(:mode,mode)',['mode' => 3])
                ->order('house_level desc')
                ->field('house_level')->find();


            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage());
        }

    }

    //房主的房源详情
    public function manageinfo($house_id,$user_id)
    {
        $house_info = House::get(['house_id'=>$house_id,'user_id'=>$user_id]);

        if (!$house_info){
            throw new \Exception('不属于当前用户房源');
        }

        if ($house_info['receive_time']){
            $house_info['receive_time'] = json_decode($house_info['receive_time'],true);
        }

        if ($house_info['stay_discount']){
            $house_info['stay_discount'] = json_decode($house_info['stay_discount'],true);
        }

        if ($house_info['group_weekday_price']){
            $group_weekday_price = json_decode($house_info['group_weekday_price'],true);
            $house_info['group_weekday_price'] = $group_weekday_price;
        }

        if ($house_info['group_weekend_price']){
            $group_weekend_price = json_decode($house_info['group_weekend_price'],true);
            $house_info['group_weekend_price'] = $group_weekend_price;
        }

        if ($house_info['group_highday_price']){
            $group_highday_price = json_decode($house_info['group_highday_price'],true);
            $house_info['group_highday_price'] = $group_highday_price;
        }

        if ($house_info['group_stay_discount']){
            $house_info['group_stay_discount'] = json_decode($house_info['group_stay_discount'],true);
        }

        $media_json = HouseMedia::where(['house_id'=>$house_id])->select();
        $house_info['media_json'] = $media_json;

        $bed_info = HouseBedInfo::where(['house_id'=>$house_id])->select();
        $house_info['bed_info'] = $bed_info;

        $complement_json = HouseComplementPrice::where(['house_id'=>$house_id])->select();
        $house_info['complement_json'] = $complement_json;

        //$park_info = HousePark::get(['house_id'=>$house_id]);
        //$park_info['media_json'] = HouseParkMedia::where(['park_id'=>$park_info['park_id']])->select();

        $data = [
            'house_info'=>$house_info,
            //'park_info'=>$park_info
        ];

        return $data;
    }

    //房源详情
    public function info($params)
    {
        //house_attr 房屋属性,0私人住宅(共享民居),1营运民宿(共享民宿),2酒店客房(共享酒店)
        //mode 共享模式,0整房共享,2拼房共享,3免费换房

        $house_id = isset($params['house_id']) ? $params['house_id'] : 0;
        //$checkin_date = isset($params['checkin_date']) ? $params['checkin_date'] : date('Y-m-d');//入住日期
        //$leave_date = isset($params['leave_date']) ? $params['leave_date'] : date('Y-m-d', strtotime(date('Y-m-d') . ' +1 day'));//离开日期

        $field = 'house_id,user_id,house_title,address,lat,lng,province,city,house_number,area,community,house_attr,bedroom_num,livingroom_num,
        kitchen_num,bathroom_num,house_type_id,house_level,mode,live_start_date,live_end_date,house_facilities_id,min_live_day,max_live_day,
        live_time,leave_time,receive_time,sheet_change,clean,share_weekday_price,share_weekend_price,share_highday_price,stay_discount,
        group_weekday_price,group_weekend_price,group_highday_price,is_group,score,zan_num,collect_num,repost_num,comment_num';

        $house_info = House::where(['house_id'=>$house_id])->field($field)->find();
        if (!$house_info){
            throw new \Exception('该房源不存在');
        }

        if ($house_info['receive_time']){
            $house_info['receive_time'] = json_decode($house_info['receive_time'],true);
        }

        if ($house_info['stay_discount']){
            $house_info['stay_discount'] = json_decode($house_info['stay_discount'],true);
        }

        if ($house_info['group_weekday_price']){
            $group_weekday_price = json_decode($house_info['group_weekday_price'],true);
            foreach ($group_weekday_price as $kk=>$vv){
                if ($vv['type']=='all'){
                    $group_weekday_price[$kk]['title'] = '整房';
                } else {
                    $group_weekday_price[$kk]['title'] = '卧室'.$vv['type'];
                }
            }
            $house_info['group_weekday_price'] = $group_weekday_price;
        }

        if ($house_info['group_weekend_price']){
            $group_weekend_price = json_decode($house_info['group_weekend_price'],true);
            foreach ($group_weekend_price as $kk=>$vv){
                if ($vv['type']=='all'){
                    $group_weekend_price[$kk]['title'] = '整房';
                } else {
                    $group_weekend_price[$kk]['title'] = '卧室'.$vv['type'];
                }
            }
            $house_info['group_weekend_price'] = $group_weekend_price;
        }

        if ($house_info['group_highday_price']){
            $group_highday_price = json_decode($house_info['group_highday_price'],true);
            foreach ($group_highday_price as $kk=>$vv){
                if ($vv['type']=='all'){
                    $group_highday_price[$kk]['title'] = '整房';
                } else {
                    $group_highday_price[$kk]['title'] = '卧室'.$vv['type'];
                }
            }
            $house_info['group_highday_price'] = $group_highday_price;
        }

        //图片
        $media_list = [];
        $media_category = HouseMediaCategory::where(['type'=>0])->order('weigh desc')->field('id,name')->select();
        foreach ($media_category as $k=>$v){
            $list = HouseMedia::where(['house_id'=>$house_id,'category_id'=>$v['id']])->field('media')->select();

            if (count($list)>0){
                $media_list[] = [
                    'title'=>$v['name'],
                    'data'=>$list
                ];
            }
        }
        $house_info['media_list'] = $media_list;
        //房屋设施
        //$house_facilities_model = new HouseFacilities();
        //$type_list = $house_facilities_model->getTypeList();
        $type_list = HouseFacilitiesCategory::order('weigh desc')->select();
        $facilities_list = [];
        foreach ($type_list as $k=>$v){
            $list = HouseFacilities::where(['category_id'=>$v['id']])->order('weigh desc')->field('name')->select();
            if (count($list)>0){
                $facilities_list[] = [
                    'title'=>$v['name'],
                    'data'=>$list
                ];
            }
        }
        $house_info['facilities_list'] = $facilities_list;
        //房屋的床铺列表
        $house_info['bed_list'] = HouseBedInfo::where(['house_id'=>$house_id])->select();

        //房屋的服务项目
        $house_info['complement'] = HouseComplementPrice::where(['house_id'=>$house_id])->select();

        $park_info = HousePark::get(['house_id'=>$house_id]);
        if (!$park_info){
            throw new \Exception('园区不存在');
        }

        $park_model = new HousePark();
        $park_info = $park_model->getInfo($park_info['park_id']);

        //业主信息  酒店不展示
        /*if ($house_info['house_attr']!=2){

        }*/
        $house_info['owner'] = User::where(['id'=>$house_info['user_id']])
            ->field('id,nickname,avatar,gender,birthday,personal_intro,job,hobby')->find();

        $data = [
            'house_info'=>$house_info,
            'park_info'=>$park_info
        ];

        return $data;
    }

    //根据入住日期和离开日期查询整屋房屋是否可住
    public function canCheckin($data)
    {
        $house_id = $data['house_id'];
        $checkin_date = $data['checkin_date'];
        $leave_date = $data['leave_date'];

        if ($checkin_date&&$leave_date){
            $house_info = HouseModel::get($house_id);
            $order_list = collection(HouseOrder::where(['house_id'=>$house_id])
                ->where('order_status','in','1,2')
                ->field('checkin_date,leave_date')->select())->toArray();

            /*if ($house_info['live_start_date']&&$house_info['live_end_date']){
                array_push($order_list,['checkin_date'=>$house_info['live_start_date'],'leave_date'=>$house_info['live_end_date']]);
            }*/

            $user_dates = $this->generate_dates($checkin_date, $leave_date);
            array_pop($user_dates);

            $conflict = $this->check_conflict($order_list, $user_dates);

            if ($conflict) {
                return 0;
                //echo "抱歉，您选择的日期与已订房的时间冲突。";
            } else {
                return 1;
                //echo "可以预订！";
            }
        }
        return 1;
    }



    //根据入住日期和离开日期查询房屋拼房状态
    public function pinfangStatus($data)
    {
        $house_id = $data['house_id'];
        $checkin_date = $data['checkin_date'];
        $leave_date = $data['leave_date'];
        if ($checkin_date&&$leave_date){
            $house_info = House::where(['house_id'=>$house_id])
                ->field('house_id,user_id,mode,house_attr,house_title,address,group_stay_discount,group_weekday_price,
            group_weekend_price,group_highday_price,bed_index,is_group,live_start_date,live_end_date')
                ->find();
            $order_list = collection(HouseOrder::where(['house_id'=>$house_id,'bed_id'=>0])
                ->where('order_status','in','1,2')
                ->field('house_id,checkin_date,leave_date')->select())->toArray();

            /*if ($house_info['live_start_date']&&$house_info['live_end_date']){
                array_push($order_list,['checkin_date'=>$house_info['live_start_date'],'leave_date'=>$house_info['live_end_date']]);
            }*/

            $user_dates = $this->generate_dates($checkin_date, $leave_date);
            array_pop($user_dates);

            $conflict = $this->check_conflict($order_list, $user_dates);

            if ($conflict){
                return 0;
            } else {
                //卧室列表
                $mode = explode(',',$house_info['mode']);
                //$bed_index = explode(',',$house_info['bed_index']);
                $house_bed_list = HouseBedInfo::where(['house_id'=>$house_id])
                    ->field('bed_id,house_id,index,bed_type,live_people_num,limit_people_num')
                    ->select();
                $leisure_count = 0;
                foreach ($house_bed_list as $k=>$v){
                    if (in_array(4,$mode)){
                        /*if (in_array($v['index'],$bed_index)){
                            $status_name = '自住';
                            $status = '2';
                        } else {*/
                            $conflict = $this->bedstatus($house_id,$v['bed_id'],$checkin_date,$leave_date);

                            if ($conflict){
                                $status_name = '已拼';
                                $status = '3';
                            } else {
                                $status_name = '待拼';
                                $status = '1';
                                $leisure_count++;
                            }
                        //}
                    } else {

                        $conflict = $this->bedstatus($house_id,$v['bed_id'],$checkin_date,$leave_date);

                        if ($conflict){
                            $status_name = '已拼';
                            $status = '3';
                        } else {
                            $status_name = '待拼';
                            $status = '1';
                            $leisure_count++;
                        }
                    }
                    $house_bed_list[$k]['status_name'] = $status_name;
                    $house_bed_list[$k]['status'] = $status;
                }
                if ($leisure_count == 0){
                    return 0;
                } else {
                    return 1;
                }
            }

        }
        return 1;
    }

    //查询入驻和离开日期卧室的状态
    public function bedstatus($house_id,$bed_id,$checkin_date,$leave_date)
    {
        $order_list = collection(HouseOrder::where(['house_id'=>$house_id])
            ->where('FIND_IN_SET(:bed_id,bed_id)',['bed_id' => $bed_id])
            ->where('order_status','in','1,2')
            ->field('checkin_date,leave_date')->select())->toArray();

        $user_dates = $this->generate_dates($checkin_date, $leave_date);
        array_pop($user_dates);

        $conflict = $this->check_conflict($order_list, $user_dates);

        return $conflict;
    }

    // 生成用户选择的日期范围
    public function generate_dates($start, $end) {
        $dates = array();
        $current = new \DateTime($start);
        while ($current <= new \DateTime($end)) {
            $dates[] = $current->format('Y-m-d');
            $current->modify('+1 day');
        }
        return $dates;
    }

    // 检查与已订房的时间是否有冲突
    public function check_conflict($booked_dates, $user_dates) {

        foreach ($booked_dates as $booking) {
            $booking_dates = $this->generate_dates($booking['checkin_date'], $booking['leave_date']);
            array_pop($booking_dates);

            // 检查是否有重叠的日期
            $overlap = array_intersect($user_dates, $booking_dates);
            if (!empty($overlap)) {
                return true;
            }
        }

        return false;
    }

    //计算房屋等级
    public function calculateHouseLevel($decorate_price,$total_price)
    {
        //普选 房屋价值<30万/装修投入<3万
        //惠选 房屋价值30-100万/装修投入3-10万
        //乐选 房屋价值100-300万/装修投入10-30万
        //优选 房屋价值300-1000万/装修投入30-100万
        //尊选 房屋价值1000万以上/装修投入100万以上
        if ($total_price>1000||$decorate_price>100){
            $level = 5;
        } elseif ($total_price>=300&&$total_price<=1000||$decorate_price>=30&&$decorate_price<=100){
            $level = 4;
        } elseif ($total_price>=100&&$total_price<=300||$decorate_price>=10&&$decorate_price<=30){
            $level = 3;
        } elseif ($total_price>=30&&$total_price<=100||$decorate_price>=3&&$decorate_price<=10){
            $level = 2;
        } elseif ($total_price<30||$decorate_price<3){
            $level = 1;
        } else {
            throw new \Exception('不满足房屋等级');
        }

        return $level;
    }

    public function calculateHouseLevelTxt($decorate_price,$total_price,$house_attr)
    {
        $house_level = $this->calculateHouseLevel($decorate_price,$total_price);

        if ($house_attr==0){
            $house_attr_txt = '民居';
        } else {
            $house_attr_txt = '民宿';
        }

        $level_arr = [
            1=>'普选',2=>'惠选',3=>'乐选',4=>'优选',5=>'尊选'
        ];

        $house_level_txt = $level_arr[$house_level].$house_attr_txt;

        return $house_level_txt;
    }
}
